/*
 * @Author: asushiye
 * @Date: 2020-07-03 08:51:09
 * @Commit: file content
 */
import { Injectable, OnInit } from '@angular/core';
import { AfMessageService, gw_code_g } from '@core';
import { SettingsService, _HttpClient } from '@delon/theme';
import { Observable } from 'rxjs';
import { format } from 'sql-formatter';

import { CgDataBaseService } from './database/databasse/cg-database.service';
import { NodeType, OptType } from './meta/meta-info';

@Injectable({
  providedIn: 'root'
})
export class CodeGenService {
  constructor(
    private http: _HttpClient,
    private msg: AfMessageService,
    private dbServ: CgDataBaseService,
    private setting: SettingsService
  ) {}

  public get httpClient(): _HttpClient {
    return this.http;
  }

  public get userName(): string | undefined {
    return this.setting.user?.name;
  }

  isEmpty(value: any): boolean {
    if (value === null || value == undefined || value === '') {
      return true;
    }
    return false;
  }

  // db2" | "mariadb" | "mysql" | "n1ql" | "plsql" | "postgresql" | "redshift" | "spark" | "sql" | "tsql" | u
  sqlformat(value: string, dbType?: any) {
    let lang: any = 'sql';
    if (dbType == 'mysql') {
      lang = 'mysql';
    } else if (dbType == 'postgresql') {
      lang = 'postgresql';
    } else if (dbType == 'oracle') {
      lang = 'plsql';
    } else if (dbType == 'flink') {
      lang = 'spark';
    } else if (dbType == 'maxcompute1') {
      lang = 'sql';
    } else if (dbType == 'maxcompute2') {
      lang = 'sql';
    } else if (dbType == 'hologres') {
      lang = 'postgresql';
    } else if (dbType == 'sqlserver') {
      lang = 'tsql';
    }

    try {
      let sql = format(value, { language: lang });
      return sql;
    } catch (e) {
      console.error(e);
      return value;
    }
  }

  // 已上传文件url 目前支持三种， tablelist, datasource, datatype,datatype-mapping
  public getUploadUrl(params: any, extendedFields: string): string {
    return `${gw_code_g}/excel/upload?sourceId=${params.sourceId}&title=${params.title}&business=${params.business}&action=insert&extendedFields=${extendedFields}`;
  }
  // 下载模板文件 目前支持三种， tablelist, datasource, datatype
  public downloadTemplateFile(business: string) {
    window.open(`${gw_code_g}/excel/download/template?business=${business}`);
  }

  public getDataSource(): Observable<any> {
    return this.http.get(`${gw_code_g}/db/datasource/select`);
  }
  public getDataSourceCascader(): Observable<any> {
    return this.http.get(`${gw_code_g}/db/datasource/cascader`);
  }

  public getCodeFromLookup(type: string): Observable<any> {
    return this.http.get(`${gw_code_g}/lookup/code/${type}`);
  }

  //基础配置 - 数据库
  public queryDataBaseAll(): Observable<any> {
    return this.dbServ.querySimpleAll();
  }

  //基础配置 - 数据类型
  public query(params: any): Observable<any> {
    console.log(JSON.stringify(params));
    return this.http.get(`${gw_code_g}/db/datatype/query`, params);
  }

  public delete(id: any): Observable<any> {
    return this.http.get(`${gw_code_g}/db/datatype/delete/${id}`);
  }

  public getUnifiedDataTpe(): Observable<any> {
    return this.http.get(`${gw_code_g}/db/datatype/unified`);
  }

  public getDataTypeList(): Observable<any> {
    return this.http.get(`${gw_code_g}/lookup/datatype/list`);
  }

  viewJson(record: any = {}) {
    const tmp = JSON.parse(JSON.stringify(record));
    tmp._values = '';
    this.msg.msg_info(JSON.stringify(tmp));
  }

  // ---- Meta元数据api
  public queryFolderTree(wsId: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/folder/tree/query?workspaceId=${wsId}`);
  }

  //新增/修改后保存节点
  public saveFolder(body: any): Observable<any> {
    return this.http.post(`${gw_code_g}/meta/folder/save`, body);
  }

  public saveFolderOrRename(body: any, optType: string): Observable<any> {
    if (optType == OptType.rename) {
      return this.http.post(`${gw_code_g}/meta/all/rename`, body);
    } else {
      return this.http.post(`${gw_code_g}/meta/folder/save`, body);
    }
  }

  public deleteNote(id: any, noteType: string): Observable<any> {
    if (noteType == NodeType.folder) {
      return this.http.get(`${gw_code_g}/meta/folder/delete/${id}`);
    } else {
      return this.http.get(`${gw_code_g}/meta/all/delete/${id}`);
    }
  }

  public deleteFolder(id: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/folder/delete/${id}`);
  }
  public deleteAll(id: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/all/delete/${id}`);
  }

  public dropTree(id: any, newPid: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/folder/tree/drop?id=${id}&newPid=${newPid}`);
  }

  //新增/修改后保存表
  public saveTableInfo(body: any): Observable<any> {
    return this.http.post(`${gw_code_g}/meta/table/info/save`, body);
  }

  public queryTableInfo(id: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/table/info/get/${id}`);
  }

  public deleteTableInfo(id: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/table/info/delete/${id}`);
  }

  public importMetaParseSql(dbType: any, body: any): Observable<any> {
    return this.http.post(`${gw_code_g}/meta/table/info/parse/sql`, body, { dbType: dbType });
  }

  public importMetaParseJson(body: any): Observable<any> {
    return this.http.post(`${gw_code_g}/meta/table/info/parse/json`, body);
  }

  public importFromDataBase(dbSource: any, tableName: any, folderId: any, wsId: any): Observable<any> {
    return this.http.get(
      `${gw_code_g}/meta/table/info/parse/database?dbSource=${dbSource}&tableName=${tableName}&folderId=${folderId}&workspaceId=${wsId}`
    );
  }
  public updateColumnFromDataBase(dbSource: any, tableName: any, tableId: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/table/column/update/database?dbSource=${dbSource}&tableName=${tableName}&tableId=${tableId}`);
  }

  public importFromMetaTable(newTableName: any, tableId: any, folderId: any, wsId: any): Observable<any> {
    return this.http.get(
      `${gw_code_g}/meta/table/info/parse/meta?newTableName=${newTableName}&tableId=${tableId}&folderId=${folderId}&workspaceId=${wsId}`
    );
  }

  public getColumnInfo(tableId: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/column/by/table/${tableId}`);
  }

  public getWorkspace(): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/workspace/all`);
  }

  public queryWorkspaceUser(wsid: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/workspace/find/username/${wsid}`);
  }
  public saveWorkspace(body: any): Observable<any> {
    return this.http.post(`${gw_code_g}/meta/workspace/save`, body);
  }
  public saveWorkspaceUser(wsIds: any, usernames: any): Observable<any> {
    return this.http.post(`${gw_code_g}/meta/workspace/username/save?wsIds=${wsIds}&usernames=${usernames}`);
  }

  public findWorkspaceByUser(username: any): Observable<any> {
    return this.http.get(`${gw_code_g}/meta/workspace/by/user/${username}`);
  }
}
